package com.itheima.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import com.itheima.bos.domain.constant.Constant;
import com.itheima.bos.utils.MailUtils;
import com.itheima.bos.web.common.BaseAction;
import com.itheima.crm.domain.Customer;

public class CustomerAction extends BaseAction<Customer> {

	// 注入消息对象
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	// 发送验证码到短信p
	@Action(value = "customer_sendSms")
	public String sendSms() {
		// 生成短信验证码
		String smsCode = RandomStringUtils.randomNumeric(4);
		// 将短信验证码保存到session中
		ServletActionContext.getRequest().getSession()
				.setAttribute(model.getTelephone(), smsCode);
		System.out.println("短信验证码" + smsCode);
		// 编写短信内容
		final String sendSms = "你好，验证码" + smsCode + "服务电话为：400212455";
		// mq发送短信
		jmsTemplate.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("sendSms", sendSms);
				return mapMessage;
			}
		});
		return NONE;
	}

	// 获取前端短信验证码
	private String checkCode;

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	// 注入redisTemplate
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	// 客户注册
	@Action(value = "customer_register", results = {
			@Result(name = "success", location = "signup-success.html", type = "redirect"),
			@Result(name = "input", location = "signup.html", type = "redirect") })
	public String register() {
		// 进行短信验证码校验
		String checkCodeSession = (String) ServletActionContext.getRequest()
				.getSession().getAttribute(model.getTelephone());
		if (checkCodeSession == null || !checkCodeSession.equals(checkCode)) {
			// 校验失败
			return INPUT;
		}

		// 调用crm系统通过
		WebClient
				.create(Constant.CRM_MANAGEMENT_URL
						+ "/services/customerService/customer")
				.type(MediaType.APPLICATION_JSON).post(model);

		// 生成32位邮箱验证
		String mailCode = RandomStringUtils.randomNumeric(32);
		// 用md5将手机号码加密成字符串
		// String idtel = Md5Utils.md5(model.getTelephone());
		// 将激活码存入数据库,24小时候自动失效
		redisTemplate.opsForValue().set(model.getTelephone(), mailCode, 24,
				TimeUnit.HOURS);
		// 调用mailUtils工具发送短信
		String content = "尊敬的用户你好，请您于24小时内点击链接地址完成绑定:<a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&mailCode=" + mailCode + "'>速运快递绑定地址</a>";
		MailUtils.sendMail("速运快递", content, model.getEmail());
		return SUCCESS;
	}

	// 邮箱验证码
	private String mailCode;

	public void setMailCode(String mailCode) {
		this.mailCode = mailCode;
	}

	@Action(value = "customer_activeMail")
	public String activeMail() throws IOException {
		// 解决中文乱码
		ServletActionContext.getResponse().setContentType(
				"text/html,charset=utf-8");
		;
		// 查询redis中的验证码，根据idtel
		String mailCheckCode = redisTemplate.opsForValue().get(
				model.getTelephone());
		// 判断激活码是否有效
		if (mailCheckCode != null || mailCode.equals(mailCheckCode)) {
			// 激活码有效
			// 调用crm_manager查询客户信息
			Customer customer = WebClient
					.create(Constant.CRM_MANAGEMENT_URL
							+ "/services/customerService/customer/telephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			System.out.println(model.getTelephone());
			// 判断邮箱是否进行认证
			if (customer.getType() == null || customer.getType() != 1) {
				// 没有认证
				WebClient.create(
						Constant.CRM_MANAGEMENT_URL + "/services/"
								+ "customerService/customer/updatetype/"
								+ model.getTelephone()).get();
				ServletActionContext.getResponse().getWriter().write("绑定成功！");
			} else {
				// 进行认证了
				ServletActionContext.getResponse().getWriter()
						.write("邮箱绑定过了，不能重复绑定");
			}

			// 删除邮箱验证码
			redisTemplate.delete(model.getTelephone());

		} else {
			// 激活码无效
			ServletActionContext.getResponse().getWriter()
					.write("激活码无效,请登录系统重新进行绑定");
		}

		return NONE;
	}

	// 客户登录功能
	@Action(value = "customer_login", results = {
			@Result(name = "success", type = "redirect", location = "index.html#/myhome"),
			@Result(name = "login", type = "redirect", location = "login.html") })
	public String login() {

		// 调用crm系统
		Customer customer = WebClient
				.create(Constant.CRM_MANAGEMENT_URL
						+ "/services/customerService/customer/login?telephone="
						+ model.getTelephone() + "&password="
						+ model.getPassword())
				.accept(MediaType.APPLICATION_JSON).get(Customer.class);

		// 是否登录成功
		if (customer == null) {
			// 登录失败
			return LOGIN;
		} else {
			// 登录成功
			ServletActionContext.getRequest().getSession()
					.setAttribute("customer", customer);
			return SUCCESS;
		}
	}
}
